<?php
/**
 * (ajax)
 */
namespace App\Admin\Ajax\Products;

use App\Models\Basics\SupplierM;
use App\Models\Product\ProductMaterial;
use App\Models\Product\ProductSupplierM;
use Illuminate\Support\Facades\DB;
class MaterialAjax{

    /**
     * 添加材料供应商 (view视图)
     */
    public function addMaterialSupplier($id){
        return view('products.material.supplier', compact('id'));
    }

    /**
     * 添加材料供应商
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function doAddMaterialSupplier($param){

        if (!$param) return response()->json(['status' => false, 'message' => '数据异常！']);
        try{
            $materialId = $param['material_id'];
            unset($param['material_id']);
            $materialCount = ProductMaterial::query()->where('id',$materialId)->count();
            if($materialCount == 0) return response()->json(['status' => false, 'message' => '材料异常！']);
            DB::beginTransaction();
            foreach ($param as $val){
                $supplierCount = SupplierM::query()->where('id',$val['supplier_id'])->count();
                if ($supplierCount == 0) throw new \Exception($val['supplier_id'].',供应商异常!');
                $productSupplierMCount = ProductSupplierM::query()
                    ->where([
                        'material_id' => $materialId,
                        'supplier_id' => $val['supplier_id']
                    ])
                    ->count();
                if ($productSupplierMCount > 0) throw new \Exception($val['supplier_id'].',系统已存在该材料说明书!');

                $flag1 = ProductSupplierM::query()->create([
                    'supplier_id' => $val['supplier_id'],
                    'material_id' => $materialId,
                    'supplier_material_no' => strtoupper($val['supplier_material_no']),
                ]);
                if(!$flag1){
                    throw new \Exception($val['supplier_id'].',更新失败!');
                }
            }
            DB::commit();
            return response()->json(['status' =>true, 'message' => '更新成功！']);

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }

}
